package com.ruoyi.fk.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.fk.domain.QuestionBankVO;
import com.ruoyi.youyou.service.ISysYouYouUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fk.domain.QuestionBank;
import com.ruoyi.fk.domain.BankQuestionMapping;
import com.ruoyi.fk.service.IQuestionBankService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 题库管理Controller
 * 
 * @author fengkun
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/fk/question_bank")
public class QuestionBankController extends BaseController
{
    @Autowired
    private IQuestionBankService questionBankService;
    @Autowired
    private ISysYouYouUserService sysYouYouUserService;


    /**
     * 查询题库管理列表
     */
//    @PreAuthorize("@ss.hasPermi('fk:question_bank:list')")
    @GetMapping("/list")
    public TableDataInfo list(QuestionBank questionBank)
    {
        startPage();
        List<QuestionBank> list = questionBankService.selectQuestionBankList(questionBank);
        return getDataTable(list);
    }

    //章节练习查询
    @PreAuthorize("@ss.hasPermi('fk:question_bank:list')")
    @GetMapping("/chapterList")
    public TableDataInfo chapterList(QuestionBankVO questionBankVO)
    {
        startPage();
        List<QuestionBankVO> list = questionBankService.selectQuestionBankChapterList(questionBankVO);
        return getDataTable(list);
    }
    //章节练习查询，vue端，用id查
    @PreAuthorize("@ss.hasPermi('fk:question_bank:list')")
    @GetMapping("/chapterById/{id}")
    public AjaxResult chapterById(@PathVariable("id") Integer id)
    {
        QuestionBankVO result = questionBankService.selectQuestionBankChapterById(id);
        return success(result);
    }

    /**
     * 导出题库管理列表
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:export')")
    @Log(title = "题库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QuestionBank questionBank)
    {
        List<QuestionBank> list = questionBankService.selectQuestionBankList(questionBank);
        ExcelUtil<QuestionBank> util = new ExcelUtil<QuestionBank>(QuestionBank.class);
        util.exportExcel(response, list, "题库管理数据");
    }

    /**
     * 获取题库管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(questionBankService.selectQuestionBankById(id));
    }

    /**
     * 新增题库管理
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:add')")
    @Log(title = "题库管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QuestionBank questionBank)
    {
        return toAjax(questionBankService.insertQuestionBank(questionBank));
    }

    /**
     * 修改题库管理
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:edit')")
    @Log(title = "题库管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QuestionBank questionBank)
    {
        return toAjax(questionBankService.updateQuestionBank(questionBank));
    }

    /**
     * 删除题库管理
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:remove')")
    @Log(title = "题库管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(questionBankService.deleteQuestionBankByIds(ids));
    }

    /**
     * 根据题库ID查询相关联的题目信息
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:edit')")
    @GetMapping("/questions/{bankId}")
    public AjaxResult getQuestionsByBankId(@PathVariable("bankId") Integer bankId)
    {
        List<Map<String, Object>> questions = questionBankService.selectQuestionsByBankId(bankId);
        return success(questions);
    }

    /**
     * 批量添加题库题目关联
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:edit')")
    @PostMapping("/batchAddQuestions")
    public AjaxResult batchAddQuestions(@RequestBody List<BankQuestionMapping> mappings)
    {
        try {
            int result = questionBankService.batchInsertBankQuestionMapping(mappings);
            if (result > 0) {
                return success("成功添加 " + result + " 个关联关系");
            } else {
                return error("添加失败，可能是关联关系已存在");
            }
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry")) {
                return error("部分题目已经关联到该题库，请检查后重试");
            }
            return error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除题库题目关联
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:edit')")
    @PostMapping("/batchRemoveQuestions")
    public AjaxResult batchRemoveQuestions(@RequestBody List<BankQuestionMapping> mappings)
    {
        int result = questionBankService.batchDeleteBankQuestionMapping(mappings);
        return toAjax(result);
    }

    /**
     * 根据题库ID删除所有关联的题目
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:edit')")
    @DeleteMapping("/questions/{bankId}")
    public AjaxResult removeAllQuestionsByBankId(@PathVariable("bankId") Integer bankId)
    {
        int result = questionBankService.deleteQuestionsByBankId(bankId);
        return toAjax(result);
    }

    /**
     * 查询题库中未关联的题目
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:edit')")
    @GetMapping("/unlinkedQuestions/{bankId}")
    public AjaxResult getUnlinkedQuestions(@PathVariable("bankId") Integer bankId, 
                                         @RequestParam Map<String, Object> params)
    {
        params.put("bankId", bankId);
        List<Map<String, Object>> questions = questionBankService.selectUnlinkedQuestions(params);
        return success(questions);
    }

    /**
     * 根据科目ID查询题库列表
     */
    @GetMapping("/listBySubjectId/{subjectId}")
    public TableDataInfo listBySubjectId(@PathVariable("subjectId") Integer subjectId)
    {
        startPage();
        QuestionBank questionBank = new QuestionBank();
        questionBank.setSubjectId(subjectId);
        questionBank.setDel(1); // 只查询未删除的题库
        List<QuestionBank> list = questionBankService.selectQuestionBankList(questionBank);
        return getDataTable(list);
    }

    /**
     * 根据科目ID查询题库列表（不分页）
     */
    @GetMapping("/listBySubjectIdNoPage/{subjectId}")
    public AjaxResult listBySubjectIdNoPage(@PathVariable("subjectId") Integer subjectId)
    {
        QuestionBank questionBank = new QuestionBank();
        questionBank.setSubjectId(subjectId);
        questionBank.setDel(1); // 只查询未删除的题库
        List<QuestionBank> list = questionBankService.selectQuestionBankList(questionBank);
        return success(list);
    }

    /**
     * 检查用户是否购买指定题库
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:query')")
    @GetMapping("/checkUserPurchase")
    public AjaxResult checkUserPurchase(@RequestParam("userId") Long userId, 
                                      @RequestParam("questionBankId") Integer questionBankId)
    {
        boolean hasPurchased = questionBankService.checkUserQuestionBankPurchase(userId, questionBankId);
        return success(hasPurchased);
    }

    /**
     * 获取用户的题库列表
     */
    @PreAuthorize("@ss.hasPermi('fk:question_bank:list')")
    @GetMapping("/questionBankList/{userId}")
    public List<QuestionBank> getQuestionBankListByUserId(@PathVariable Long userId) {
        return sysYouYouUserService.selectQuestionBankListByUserId(userId);
    }

}
